package com.example.sneakerappforme1105;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.example.sneakerappforme1105.bean.Cart;
import com.example.sneakerappforme1105.bean.User;
import com.example.sneakerappforme1105.constant.NetConst;
import com.example.sneakerappforme1105.dao.CartDao;
import com.example.sneakerappforme1105.dao.UserDao;
import com.example.sneakerappforme1105.util.SharedUtil;
import com.example.sneakerappforme1105.util.ToastUtil;

import org.json.JSONObject;

import java.io.IOException;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {
    private String TAG = "login";
    private EditText et_username;
    private EditText et_password;
    private UserDao userDao; // 用来处理登录
    private CartDao cartDao;

    private CheckBox ck_rem; // 声明一个复选框对象
    private boolean isRemember = false; // 是否记住密码
    private SharedPreferences mShared; // 声明一个共享参数对象

    private OkHttpClient client;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et_username = findViewById(R.id.et_username);
        et_password = findViewById(R.id.et_password);
        userDao = MainApplication.getInstance().getAppDatabase().userDao();
        cartDao = MainApplication.getInstance().getAppDatabase().cartDao();
        ck_rem = findViewById(R.id.ck_rem);
        ck_rem.setOnCheckedChangeListener((buttonView, isChecked)->isRemember = isChecked);
        mShared = getSharedPreferences("user_info", MODE_PRIVATE);

        // 读取保存的用户名和密码
        String savedUsername = mShared.getString("username", "");
        String savedPassword = mShared.getString("password", "");
        boolean isRemembered = mShared.getBoolean("isRemember", false);

        if (isRemembered) {
            et_username.setText(savedUsername);
            et_password.setText(savedPassword);
            ck_rem.setChecked(true);
        }

        client = new OkHttpClient();
        findViewById(R.id.button_log).setOnClickListener(view -> {
            // 登录按钮监听  登录成功，跳转到商城页面
            String username = et_username.getText().toString();
            String password = et_password.getText().toString();
            if(username.equals("") || password.equals("")) {
                Toast.makeText(this, "用户名或密码不能为空(!_!)", Toast.LENGTH_SHORT).show();
            } else if(password.length()>=8){


                performLogin(username, password);

            }else{
                Toast.makeText(this, "密码长度小于8位", Toast.LENGTH_SHORT).show();
            }
        });

        findViewById(R.id.button_sign).setOnClickListener(view -> {
            // 注册按钮监听  跳转到注册页面  signUpActivity
            Intent intent = new Intent(this, SignUpActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);    // 返回后登录
            startActivity(intent);
        });

    }

    private void performLogin(String username, String password) {

        RequestBody body = new FormBody.Builder()
                .add("username", username)
                .add("password", password)
                .build();


        Request request = new Request.Builder()
                .url(NetConst.HTTP_PREFIX+"login")
                .post(body)
                .build();


        // 发送请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                runOnUiThread(() -> Toast.makeText(MainActivity.this, "网络错误，请稍后再试", Toast.LENGTH_SHORT).show());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {  // 状态码 200
                    String responseData = response.body().string();
                    handleLoginResponse(responseData);  //返回的数据
                } else {
                    runOnUiThread(() -> Toast.makeText(MainActivity.this, "登录失败，服务器错误", Toast.LENGTH_SHORT).show());
                }
            }
        });
    }



    private void handleLoginResponse(String responseData) {
        try {
            JSONObject jsonResponse = new JSONObject(responseData);
            int code = jsonResponse.getInt("code"); // 200 404
            String message = jsonResponse.getString("message"); // failed

            if (code == 200) { // 登录成功
                JSONObject data = jsonResponse.getJSONObject("data");
                long userId = data.getLong("userId");
                long cartId = data.getLong("cartId");
                int role = data.getInt("role");// 权限

                // 保存用户名和密码
                if (isRemember) {
                    SharedPreferences.Editor editor = mShared.edit();
                    editor.putString("username", et_username.getText().toString());
                    editor.putString("password", et_password.getText().toString());
                    editor.putBoolean("isRemember", true);
                    editor.apply();
                } else {
                    // 清除保存的用户名和密码
                    SharedPreferences.Editor editor = mShared.edit();
                    editor.clear();
                    editor.apply();
                }

                runOnUiThread(() -> {
                    Toast.makeText(MainActivity.this, "登录成功！", Toast.LENGTH_SHORT).show();
                    if(role==0) {   // 跳入用户
                        Intent intent = new Intent(MainActivity.this, RootActivity.class);
                        intent.putExtra("userId", userId);
                        intent.putExtra("cartId", cartId);
                        startActivity(intent);
                    }else{
                        // role =1 进入商家页
                        Intent intent = new Intent(MainActivity.this, SaleActivity.class);
                        intent.putExtra("userId", userId);
                        startActivity(intent);
                    }
                });
            } else { // 登录失败
                runOnUiThread(() -> Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show());
            }
        } catch (Exception e) {
            e.printStackTrace();
            runOnUiThread(() -> Toast.makeText(MainActivity.this, "解析错误", Toast.LENGTH_SHORT).show());
        }
    }



}